package com.guguskins.back.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.guguskins.back.common.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
@Slf4j
public class OSSUtil {

    /**
     * oss处访问图片的 url
     */
    private static String address;

    /**
     * oss的 endpoint
     */
    private static String endPoint;


    private static String accessKey;


    private static String secretKey;

    /**
     * oss的储存名称
     */
    private static String bucket;

    /**
     * 上传MultipartFile文件
     */
    public static String uploadMultipartFile(MultipartFile multipartFile, String dir, boolean flag) {
        InputStream multipartFileInputStream;
        try {
            multipartFileInputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            log.error("获取输入流失败", e);
            throw new GlobalException(e);
        }
        String fileName = generateFileName(multipartFile);
        String key = fileName;
        if (!ObjectUtils.isEmpty(dir)) {
            key = dir + "/" + fileName;
        }
        if (flag) {
            //上传webp
            uploadImageWebp(multipartFile, dir, fileName);
        }
        return uploadInputSteam(key, multipartFileInputStream);
    }

    /**
     * 上传图片webp格式
     */
    public static void uploadImageWebp(MultipartFile multipartFile, String dir, String fileName) {
        InputStream multipartFileInputStream;
        try {
            multipartFileInputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            log.error("获取输入流失败", e);
            throw new GlobalException(e);
        }

        String key = fileName;
        if (!ObjectUtils.isEmpty(dir)) {
            key = dir + "/" + fileName + ".webp";
        }
        uploadInputSteam(key, multipartFileInputStream);
    }

    /**
     * 上传输入流
     */
    private static String uploadInputSteam(String key, InputStream inputStream) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKey, secretKey);

        // 创建PutObjectRequest对象。
        // 填写Bucket名称、Object完整路径和本地文件的完整路径。Object完整路径中不能包含Bucket名称。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。


        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, inputStream);

        // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
        // ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        // metadata.setObjectAcl(CannedAccessControlList.Private);
        // putObjectRequest.setMetadata(metadata);

        // 上传文件。
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();
        return address + "/" + key;
    }

    private static String generateFileName(MultipartFile multipartFile) {
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        return UUID.randomUUID().toString().replaceAll("-", "") + suffix;
    }


    @Value("${aliyun.oss.address}")
    public void setAddress(String address) {
        OSSUtil.address = address;
    }

    @Value("${aliyun.oss.end-point}")
    public void setEndPoint(String endPoint) {
        OSSUtil.endPoint = endPoint;
    }

    @Value("${aliyun.oss.access-key}")
    public void setAccessKey(String accessKey) {
        OSSUtil.accessKey = accessKey;
    }

    @Value("${aliyun.oss.secret-key}")
    public void setSecretKey(String secretKey) {
        OSSUtil.secretKey = secretKey;
    }

    @Value("${aliyun.oss.bucket}")
    public void setBucket(String bucket) {
        OSSUtil.bucket = bucket;
    }
}
